package org.agent.aigccore.dao.impl;

import jakarta.annotation.Resource;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.agent.aigccore.basic.enums.IotDeviceStatusEnum;
import org.agent.aigccore.basic.enums.IotDeviceWorkStatusEnum;
import org.agent.aigccore.dao.IotDeviceRepository;
import org.agent.aigccore.dao.mappers.mysql.IotDeviceMapper;
import org.agent.aigccore.model.bo.IotDeviceBO;
import org.agent.aigccore.model.po.IotDevicePO;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

import static org.agent.aigccore.model.bo.IotDeviceBO.convert;

@Slf4j
@Setter
@Component
public class IotDeviceRepositoryImpl implements IotDeviceRepository {

    @Resource
    private IotDeviceMapper iotDeviceMapper;

    @Override
    public IotDeviceBO load(Long id, boolean lock) {
        if (lock) {
            return convert.formPO(iotDeviceMapper.lock(id));
        }
        return convert.formPO(iotDeviceMapper.load(id));
    }

    @Override
    public List<IotDeviceBO> page(IotDeviceStatusEnum deviceStatus, IotDeviceWorkStatusEnum workStatus, int offset, int pageSize) {
        List<IotDevicePO> pos = iotDeviceMapper.page(
                deviceStatus != null ? deviceStatus.getCode() : null,
                workStatus != null ? workStatus.getCode() : null,
                offset, pageSize);
        log.info("[IotDeviceRepository.page] 召回数量={}", pos.size());
        return pos.stream().map(po -> convert.formPO(po)).collect(Collectors.toList());
    }

    @Override
    public int insert(IotDeviceBO iotDeviceBO) {
        IotDevicePO po = convert.toPO(iotDeviceBO);
        int num = iotDeviceMapper.insert(po);
        iotDeviceBO.setId(po.getId());
        log.info("[IotDeviceRepository.insert] 插入成功！num={}", num);
        return num;
    }

    @Override
    public int update(IotDeviceBO iotDeviceBO) {
        IotDevicePO po = convert.toPO(iotDeviceBO);
        int num = iotDeviceMapper.update(po);
        log.info("[IotDeviceRepository.update] 更新成功！num={}", num);
        return num;
    }

    @Override
    public int delete(Long id) {
        int num = iotDeviceMapper.delete(id);
        log.info("[IotDeviceRepository.delete] 删除成功！num={}", num);
        return num;
    }
}